#include "titlebar.h"

#include <QHBoxLayout>
#include <QDebug>
#include <usermanual.h>

Titlebar::Titlebar(QWidget *parent) : QWidget(parent)
{
    initUI();
    initMenu();
    connectInit();
}

Titlebar::~Titlebar()
{
    if (m_menu != nullptr) {
        delete m_menu;
        m_menu = nullptr;
    }
    if (m_searchServer != nullptr) {
        delete m_searchServer;
        m_searchServer = nullptr;
    }
}

void Titlebar::initUI()
{

    setObjectName("titlebar");
    m_titleNameLab = new QLabel(this);
    m_titleIcon = new QPushButton(this);
    m_titleIcon->setFixedSize(24, 24);
    m_titleIcon->setIconSize(QSize(24, 24));
    QString m_titleIconStyle = "QPushButton{border:0px;border-radius:4px;background:transparent;}"
                               "QPushButton:Hover{border:0px;border-radius:4px;background:transparent;}"
                               "QPushButton:Pressed{border:0px;border-radius:4px;background:transparent;}";
    m_titleIcon->setStyleSheet(m_titleIconStyle);
    m_titleIcon->setIcon(QIcon::fromTheme("kylin-multi-collaboration"));
    m_titleIcon->setContentsMargins(8, 8, 8, 8);

    m_searchLine = new kdk::KSearchLineEdit(this);
    m_searchLine->setClearButtonEnabled(true);
    m_searchLine->setPlaceholderText(tr("Search"));
    m_searchLine->setFocusPolicy(Qt::ClickFocus);
    m_searchLine->setContextMenuPolicy(Qt::DefaultContextMenu);
    m_searchLine->hide();

    m_searchLine->setFixedSize(230, 32);
    m_menuBtn = new QToolButton(this);
    m_menu = new QMenu();
    m_menuBtn->setToolTip(tr("Menu"));
    m_minBtn = new QPushButton(this);
    m_maxBtn = new QPushButton();
    m_closeBtn = new QPushButton(this);

    m_titleNameLab->setText(tr("kylin-connectivity"));
    // 固定高度
    setFixedHeight(40);
    setAutoFillBackground(true);

    m_menuBtn->setFocusPolicy(Qt::NoFocus);
    // 最小化按钮
    m_minBtn->setFixedSize(30, 30);
    m_minBtn->setIcon(QIcon::fromTheme("window-minimize-symbolic"));
    m_minBtn->setIconSize(QSize(16, 16));
    m_minBtn->setProperty("isWindowButton", 0x1);
    m_minBtn->setProperty("useIconHighlightEffect", 0x2);
    m_minBtn->setFlat(true);
    m_minBtn->setContentsMargins(4, 0, 4, 0);
    m_minBtn->setFocusPolicy(Qt::NoFocus);
    m_minBtn->setToolTip(tr("Minimize"));
    // 最大化按钮
    m_maxBtn->setFixedSize(30, 30);
    m_maxBtn->setIcon(QIcon::fromTheme("window-maximize-symbolic"));
    m_maxBtn->setIconSize(QSize(16, 16));
    m_maxBtn->setProperty("isWindowButton", 0x1);
    m_maxBtn->setProperty("useIconHighlightEffect", 0x2);
    m_maxBtn->setFlat(true);
    m_maxBtn->setContentsMargins(4, 0, 4, 0);
    // 关闭按钮
    m_closeBtn->setFixedSize(30, 30);
    m_closeBtn->setIcon(QIcon::fromTheme("window-close-symbolic"));
    m_closeBtn->setIconSize(QSize(16, 16));
    m_closeBtn->setProperty("isWindowButton", 0x2);
    m_closeBtn->setProperty("useIconHighlightEffect", 0x8);
    m_closeBtn->setFlat(true);
    m_closeBtn->setContentsMargins(4, 0, 4, 0);
    m_closeBtn->setFocusPolicy(Qt::NoFocus);
    m_closeBtn->setToolTip(tr("Close"));

    // 整体布局
    QHBoxLayout *layout = new QHBoxLayout;
    layout->addSpacing(8);
    layout->addWidget(m_titleIcon);
    layout->addWidget(m_titleNameLab);
    layout->addStretch();
    layout->addWidget(m_searchLine);
    layout->addStretch();
    layout->addWidget(m_menuBtn);
    layout->addWidget(m_minBtn);
    layout->addWidget(m_maxBtn);
    layout->addWidget(m_closeBtn);
    layout->addSpacing(4);
    layout->setContentsMargins(0, 4, 0, 0);

    setLayout(layout);
}

void Titlebar::hideButton()
{
    m_titleIcon->hide();
    m_titleNameLab->hide();
    m_menuBtn->hide();
    m_minBtn->hide();
    m_closeBtn->hide();
}

void Titlebar::setTheme(PublicAttributes::Theme theme)
{
    m_theme = theme;
    if (m_isDefault) {
        switch (m_theme) {
        case PublicAttributes::Theme::Light: {
            setStyleSheet("QWidget#titlebar{background-color: #FFFFFF;}");
        } break;
        case PublicAttributes::Theme::Dark: {
            setStyleSheet("QWidget#titlebar{background-color: #1D1D1D;}");
        } break;
        }
    }
}

void Titlebar::setBackground(bool isDefault)
{
    m_isDefault = isDefault;
    if (isDefault) {
        switch (m_theme) {
        case PublicAttributes::Theme::Light: {
            setStyleSheet("QWidget#titlebar{background-color: #FFFFFF;}");
        } break;
        case PublicAttributes::Theme::Dark: {
            setStyleSheet("QWidget#titlebar{background-color: #1D1D1D;}");
        } break;
        }
    } else {
        setAttribute(Qt::WA_StyledBackground);
        setStyleSheet("QWidget#titlebar{background-color: rgba(98, 142, 255, 0.1);}");
    }
}

// 连接槽
void Titlebar::connectInit()
{
    // 连接最大、小化、关闭按钮信号槽
    connect(m_minBtn, &QPushButton::clicked, this, &Titlebar::onClicked);
    connect(m_maxBtn, &QPushButton::clicked, this, &Titlebar::onClicked);
    connect(m_closeBtn, &QPushButton::clicked, this, &Titlebar::onClicked);
    // 连接菜单信号槽
    connect(m_menu, &QMenu::triggered, this, &Titlebar::triggerMenu);
    connect(m_searchLine, &kdk::KSearchLineEdit::textChanged, this, &Titlebar::onTextChanged);
    connect(m_searchLine, &kdk::KSearchLineEdit::returnPressed, this, &Titlebar::onReturnPressed);
    connect(this, &Titlebar::sigSearchLineShow, this, [this]() {
        // m_searchLine->show();
    });
}

// 设置菜单按钮
void Titlebar::initMenu()
{
    // 菜单按钮
    m_menuBtn->setFixedSize(30, 30);
    m_menuBtn->setIcon(QIcon::fromTheme("open-menu-symbolic"));
    m_menuBtn->setIconSize(QSize(16, 16));
    m_menuBtn->setProperty("isWindowButton", 0x1);
    m_menuBtn->setProperty("useIconHighlightEffect", 0x2);
    m_menuBtn->setPopupMode(QToolButton::InstantPopup);
    m_menuBtn->setAutoRaise(true);
    m_menuBtn->setContentsMargins(4, 0, 4, 0);

    // 创建Action
    QAction *actionHelp = new QAction(m_menu);
    QAction *actionAbout = new QAction(m_menu);
    QAction *actionQuit = new QAction(m_menu);
    actionHelp->setText(tr("Help"));
    actionAbout->setText(tr("About"));
    actionQuit->setText(tr("Quit"));

    // 将Action添加到菜单中
    m_actions << actionHelp << actionAbout << actionQuit;
    m_menu->addActions(m_actions);

    // 为菜单按钮设置菜单
    m_menuBtn->setMenu(m_menu);
}

// 处理点击信号
void Titlebar::onClicked()
{
    QPushButton *clickBtn = qobject_cast<QPushButton *>(sender());
    if (clickBtn == m_minBtn) {
        // 最小化
        window()->showMinimized();
    } else if (clickBtn == m_closeBtn) {
        window()->close();
    } else if (clickBtn == m_maxBtn) {
        // 当前窗口是否最大化，最大化：点击后还原，更换图标。窗口化：点击后最大化，更换图标
        if (window()->isMaximized()) {
            window()->showNormal();
            m_maxBtn->setIcon(QIcon::fromTheme("window-maximize-symbolic"));
        } else {
            window()->showMaximized();
            m_maxBtn->setIcon(QIcon::fromTheme("window-restore-symbolic"));
        }
    }
}

// Action处理
void Titlebar::triggerMenu(QAction *act)
{
    QString str = act->text();
    if (tr("Help") == str) {
        initHelp();
    } else if (tr("About") == str) {
        Q_EMIT sigAboutWinShow();
    } else if (tr("Quit") == str) {
        window()->close();
    }
}

// 帮助入口，调用用户手册
void Titlebar::initHelp()
{
    QString service_name = "com.kylinUserGuide.hotel_" + QString::number(getuid());
    QDBusMessage msg = QDBusMessage::createMethodCall(QString(service_name), KYLIN_USER_GUIDE_PATH,
                                                      KYLIN_USER_GUIDE_INTERFACE, "showGuide");
    msg << "kylin-mobile-assistant";
    if (QDBusConnection::sessionBus().isConnected())
        QDBusConnection::sessionBus().call(msg);
}

void Titlebar::onTextChanged()
{
    if (!m_mutex.try_lock()) {
        return;
    }
    if (m_searchServer == nullptr) {
        qWarning() << "search server is not ready!";
        return;
    }
    m_query = m_searchLine->text().trimmed();
    m_mutex.unlock();
    if (m_query.isEmpty()) {
        return;
    }

    auto search = [this]() {
        if (!m_mutex.try_lock()) {
            return;
        }
        Q_EMIT sigStartSearch();
        m_resultMap.clear();
        m_searchServer->search(m_resultMap, m_query);
        Q_EMIT sigSearchResult(m_resultMap);
        m_mutex.unlock();
    };
    std::thread searchThread(search);
    searchThread.detach();
}

void Titlebar::onReturnPressed()
{
    onTextChanged();
}

void Titlebar::onSearchInstalled(bool isUpdated, QString searchInfoPath)
{
    qInfo() << "searchInfo installed";

    if (!m_mutex.try_lock()) {
        return;
    }
    if (m_searchServer != nullptr) {
        m_searchLine->clear();
        delete m_searchServer;
        m_searchServer = nullptr;
    }
    m_searchServer = new SearchServer();
    m_searchServer->setSearchDbPath(searchInfoPath);
    if (m_searchServer) {
        if (m_searchServer->init() < 0) {
            qWarning() << "load search server fail";
            Q_EMIT sigSearchInitFail();
            return;
        }
    }
    m_mutex.unlock();

    if (!isUpdated) {
        qInfo() << "use old searchInfo";
        Q_EMIT sigSearchLineShow();
    } else {
        if (m_searchServer) {
            qInfo() << "use new searchInfo";
            auto searchInit = [this]() {
                m_mutex.lock();
                if (m_searchServer->createIndex() >= 0) {
                    Q_EMIT sigSearchLineShow();
                } else {
                    qWarning() << "search server init fail";
                    Q_EMIT sigSearchInitFail();
                }
                m_mutex.unlock();
            };
            std::thread searchInitThread(searchInit);
            searchInitThread.detach();
        }
    }
}

void Titlebar::hideSearchLine()
{
    qInfo() << "searchLine hide";
    m_searchLine->hide();
    m_searchLine->clear();
    if (m_searchServer != nullptr) {
        delete m_searchServer;
        m_searchServer = nullptr;
    }
}

void Titlebar::onBackButtonClick()
{
    m_searchLine->clear();
}
